import { useState, useCallback } from 'react';
import { ReauthDialog } from '@/components/auth/reauth-dialog';
import { useToast } from '@/hooks/use-toast';

interface UseTokenExpiryReturn {
  showReauthDialog: boolean;
  handleTokenExpiry: () => void;
  ReauthDialogComponent: React.ComponentType;
  closeReauthDialog: () => void;
}

export function useTokenExpiry(): UseTokenExpiryReturn {
  const [showReauthDialog, setShowReauthDialog] = useState(false);
  const { toast } = useToast();

  const handleTokenExpiry = useCallback(() => {
    setShowReauthDialog(true);
  }, []);

  const closeReauthDialog = useCallback(() => {
    setShowReauthDialog(false);
  }, []);

  const handleReauthSuccess = useCallback(() => {
    setShowReauthDialog(false);
    toast({
      title: '重新登录成功',
      description: '您可以继续使用系统',
      variant: 'default'
    });
    // 可以在这里触发页面刷新或重新加载数据
    window.location.reload();
  }, [toast]);

  const handleReauthCancel = useCallback(() => {
    setShowReauthDialog(false);
    // 可以选择跳转到登录页面
    window.location.href = '/login';
  }, []);

  const ReauthDialogComponent = useCallback(() => {
    return (
      <ReauthDialog
        open={showReauthDialog}
        onOpenChange={setShowReauthDialog}
        onSuccess={handleReauthSuccess}
        onCancel={handleReauthCancel}
      />
    );
  }, [showReauthDialog, handleReauthSuccess, handleReauthCancel]);

  return {
    showReauthDialog,
    handleTokenExpiry,
    ReauthDialogComponent,
    closeReauthDialog
  };
}

// 全局token过期处理器
let globalTokenExpiryHandler: (() => void) | null = null;

export function setGlobalTokenExpiryHandler(handler: () => void) {
  globalTokenExpiryHandler = handler;
}

export function triggerGlobalTokenExpiry() {
  if (globalTokenExpiryHandler) {
    globalTokenExpiryHandler();
  }
}